package com.glory.study.utils;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.glory.study.testinterface.HelloService;
import com.glory.study.testinterface.PayInfo;
import com.glory.study.testinterface.PayResult;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PayUtils {



    private static ApplicationConfig application = new ApplicationConfig();

    private static Map<String, RegistryConfig> registryConfigCache = new ConcurrentHashMap<>();

    private static Map<String, ReferenceConfig<HelloService>> referenceCache = new ConcurrentHashMap<>();

    static {
        application.setName("test");
    }


    private static RegistryConfig getRegistryConfig(String address,String group, String version) {
        String key = address + "-" + group + "-" + version;
        RegistryConfig registryConfig = registryConfigCache.get(key);
        if (null == registryConfig) {
            registryConfig = new RegistryConfig();
            registryConfig.setAddress(address);
            registryConfigCache.put(key, registryConfig);
        }
        return registryConfig;
    }

    /**
     * 获取服务的代理对象
     *
     */
    private static ReferenceConfig<HelloService> getReferenceConfig( String group,String address,
                                                                              String version) {
        String referenceKey = group;
        ReferenceConfig<HelloService> referenceConfig = referenceCache.get(referenceKey);
        if (null == referenceConfig) {
            referenceConfig = new ReferenceConfig<>();
            referenceConfig.setApplication(application);
            referenceConfig.setRegistry(getRegistryConfig(address, group, version));
            referenceConfig.setInterface(HelloService.class);
            referenceConfig.setVersion(version);
            referenceConfig.setGroup(group);
            referenceCache.put(referenceKey, referenceConfig);
        }
        return referenceConfig;
    }



    /**
     * 调用远程服务
     *
     */
    public static PayResult invoke(PayInfo dto) {
        String group=dto.getType();
        String add=dto.getAddress();
        String version=dto.getVersion();
        ReferenceConfig<HelloService> reference = getReferenceConfig(group, add, version);
        if (null != reference) {
            HelloService helloService = reference.get();
            if (null != helloService) {
                return helloService.pay(dto);
            }
        }
        return null;
    }
}
